package cn.ubeta.b2c.common;

import android.content.Context;
import android.content.res.Configuration;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewStub;

import cn.ubeta.b2c.R;
import cn.ubeta.b2c.bean.ApiResp;
import cn.ubeta.b2c.bean.BannerInfo;
import cn.ubeta.b2c.utils.NetworkCallback;
import cn.ubeta.b2c.utils.ToastHelper;
import cn.ubeta.b2c.widget.banner.BannerAdapter;
import cn.ubeta.b2c.widget.banner.InfiniteViewPager;
import cn.ubeta.b2c.widget.ptr.PtrCommonLayout;
import cn.ubeta.b2c.widget.recyclerview.BaseRecyclerAdapter;
import cn.ubeta.b2c.widget.recyclerview.BaseViewHolder;
import cn.ubeta.b2c.widget.viewpagerindicator.CirclePageIndicator;

import java.io.IOException;
import java.util.List;

import in.srain.cube.views.ptr.PtrDefaultHandler;
import in.srain.cube.views.ptr.PtrFrameLayout;
import in.srain.cube.views.ptr.PtrHandler;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

import static android.nfc.tech.MifareUltralight.PAGE_SIZE;

/**
 * Created by denny on 16/8/17.
 */

public abstract class ListFragment<T> extends Fragment implements PtrHandler {

    protected View mViewBanner;
    protected ViewStub mVsBanner;

    protected RecyclerView mRecyclerView;
    protected GridLayoutManager mLayoutMan;
    protected BaseRecyclerAdapter mAdapter;
    protected PtrCommonLayout mPtrCommonLayout;

    private int mPage;
    private NetworkCallback<List<T>> mNetworkCallback;
    private Callback<ApiResp<List<T>>> mCallback;
    private boolean mKeepPosition;

    public ListFragment() {
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_recyclerview, container, false);
    }

    @Override
    public void onViewCreated(View view, Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);

        mRecyclerView = (RecyclerView) view.findViewById(R.id.rv_list);
        mLayoutMan = new GridLayoutManager(getContext(), getSpanCount());
        mRecyclerView.setLayoutManager(mLayoutMan);

        mVsBanner = (ViewStub) view.findViewById(R.id.vs_banner);

        loadNew();

        // 初始化下拉刷新
        mPtrCommonLayout = (PtrCommonLayout) view.findViewById(R.id.ptr_recyclerview);
        mPtrCommonLayout.setPtrHandler(this);
    }

    /**
     * 设置banner
     */
    public void setBanner(List<BannerInfo> data) {
        if (mViewBanner == null) {
            mViewBanner = mVsBanner.inflate();
        }

        setBanner(getContext(), data, mViewBanner);
    }

    /**
     * 设置banner
     */
    public static void setBanner(Context context, List<BannerInfo> data, View root) {
        InfiniteViewPager mBannerViewPager;
        BannerAdapter mBannerAdapter = null; // TODO 复用
        CirclePageIndicator mIndicator;

        mBannerViewPager = (InfiniteViewPager) root.findViewById(R.id.banner_view_pager);
        mIndicator = (CirclePageIndicator) root.findViewById(R.id.banner_indicator);

        if (mBannerAdapter == null) {
            //ViewGroup.LayoutParams param = mBannerViewPager.getLayoutParams();
            //param.height = DeviceInfoHelper.getHeightByRadio(1);
            //mBannerViewPager.setLayoutParams(param);
            mBannerAdapter = new BannerAdapter(context, data);
            mBannerViewPager.setAdapter(mBannerAdapter);
            mIndicator.setViewPager(mBannerViewPager);
            mIndicator.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
                @Override
                public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
                }

                @Override
                public void onPageSelected(int position) {
                    if (mBannerViewPager.isAutoScroll()) {
                        mBannerViewPager.resetAutoScrollValue();
                        return;
                    }
                }

                @Override
                public void onPageScrollStateChanged(int state) {
                }
            });
        } else {
            mBannerAdapter.setData(data);
            mIndicator.notifyDataSetChanged();
        }

        if (data.size() > 1) {
            mBannerViewPager.startAutoScroll();
            mIndicator.setVisibility(View.VISIBLE);
        } else {
            mIndicator.setVisibility(View.GONE);
        }
    }

    /**
     * 获取子项布局,横向单元格个数,纵向单元格个数
     * @return
     */
    protected abstract ListFragmentConfig getConfig();

    /**
     * 绑定数据到子项视图
     * @param helper
     * @param item
     */
    protected abstract void bindItemView(BaseViewHolder helper, T item);

    /**
     * 解析数据
     * @param result
     * @return
     */
    //protected abstract List parseData(String result);

    /**
     * API的url
     * @return
     */
    protected abstract void loadData(int page);

    @Override
    public boolean checkCanDoRefresh(PtrFrameLayout frame, View content, View header) {
        return PtrDefaultHandler.checkContentCanBePulledDown(frame, mRecyclerView, header);
    }

    @Override
    public void onRefreshBegin(PtrFrameLayout frame) {
        loadNew();
    }

    /**
     * 加载新数据,不保持位置
     */
    protected void loadNew() {
        loadNew(false);
    }

    /**
     * 初始化适配器
     * @param data
     */
    private void initAdapter(List data) {
        if (getActivity() == null || getActivity().isFinishing())
            return;

        mAdapter = new BaseRecyclerAdapter<T>(getContext(), getConfig().getResItemLayout()) {
            @Override
            protected void convert(BaseViewHolder helper, T item) {
                bindItemView(helper, item);
            }
        };

        mAdapter.setNewData(data);
        mRecyclerView.setAdapter(mAdapter);
    }

    /**
     * API回调
     * @return
     */
    protected NetworkCallback<List<T>> getNetworkCallback() {
        if (mNetworkCallback == null) {
            mNetworkCallback = new NetworkCallback<List<T>>() {
                @Override
                public void onResponse(List data) {
                    boolean hasMore = false;
                    //List data = parseData(result);
                    if (data != null && data.size() > 0) {
                        if (mPage++ == 1) {
                            if (mKeepPosition && mAdapter != null) {
                                mAdapter.setNewData(data);
                            } else {
                                initAdapter(data);
                            }
                        } else {
                            mAdapter.addData(data);
                        }
                        hasMore = data.size() == PAGE_SIZE;
                    }
                    if (hasMore) {
                        // TODO 到底
                    }
                    onLoadFinish(true);
                }

                @Override
                public void onFailure(IOException e) {
                    onLoadFinish(false);
                }
            };
        }
        return mNetworkCallback;
    }

    /**
     * API回调
     * @return
     */
    protected Callback<ApiResp<List<T>>> getCallback() {
        if (mCallback == null) {
            mCallback = new Callback<ApiResp<List<T>>>() {
                @Override
                public void onResponse(Call<ApiResp<List<T>>> call, Response<ApiResp<List<T>>> res) {
                    if (res == null || res.body() == null) {
                        ToastHelper.debug("网络返回空！！！");
                        return;
                    }
                    List data = res.body().getData();

                    boolean hasMore = false;
                    //List data = parseData(result);
                    if (data != null && data.size() > 0) {
                        if (mPage++ == 1) {
                            if (mKeepPosition && mAdapter != null) {
                                mAdapter.setNewData(data);
                            } else {
                                initAdapter(data);
                            }
                        } else {
                            mAdapter.addData(data);
                        }
                        hasMore = data.size() == PAGE_SIZE;
                    }
                    if (hasMore) {
                        // TODO 到底
                    }
                    onLoadFinish(true);
                }

                @Override
                public void onFailure(Call<ApiResp<List<T>>> call, Throwable t) {
                    onLoadFinish(false);
                }
            };
        }
        return mCallback;
    }

    /**
     * 加载新数据,是否保持位置
     */
    protected void loadNew(boolean keepPosition) {
        mKeepPosition = keepPosition;
        mPage = 1;
        loadData(mPage);
    }

    /**
     * 加载数据完成
     */
    protected void onLoadFinish(boolean respOk) {
        hideRefreshing();
    }

    /**
     * 隐藏下拉刷新
     */
    private void hideRefreshing() {
        // 是否下拉刷新
        if (mPtrCommonLayout != null && mPtrCommonLayout.isRefreshing()) {
            mPtrCommonLayout.postDelayed(() -> {
                mPtrCommonLayout.refreshComplete();
            }, 10);
        }
    }

    /**
     * 获取单元格个数
     * @return
     */
    protected int getSpanCount() {
        Configuration configuration = getResources().getConfiguration();
        if (configuration.orientation == Configuration.ORIENTATION_LANDSCAPE) {
            return getConfig().getSpanLandscape();
        } else {
            return getConfig().getSpanPortrait();
        }
    }

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        if (mLayoutMan != null) {
            if (getSpanCount() != mLayoutMan.getSpanCount()) {
                mLayoutMan.setSpanCount(getSpanCount());
                // 避免crash
                // java.lang.IllegalArgumentException
                // Item at position 0 requires 4 spans but GridLayoutManager has only 2 spans.
                // use this to update the layout
                mAdapter.notifyDataSetChanged();
                // or you can use this to update the layout
                mLayoutMan.requestLayout();
            }
        }
    }

}
